package cz.data.common.support.db.source;

import cz.data.common.support.db.DbProperty;
import cz.data.common.support.db.DbType;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Slf4j
public class DataSourceRegistry {
    private static final EmptyDataSourceFactory emptyFactory = new EmptyDataSourceFactory();
    private static final Map<DbType, DataSourceFactory> registry = new HashMap<>();

    public static void register(DataSourceFactory factory, DbType... dbTypes) {
        if (Objects.nonNull(dbTypes)) {
            for (DbType dbType : dbTypes) {
                log.info("DataSourceFactory注册: {}", dbType.getDesc());
                registry.put(dbType, factory);
            }
        }
    }

    public static DataSourceFactory factory(String dbType) {
        return factory(DbType.getDbType(dbType));
    }

    public static DataSourceFactory factory(DbType dbType) {
        return Optional.ofNullable(registry.get(dbType)).orElse(emptyFactory);
    }

    private static class EmptyDataSourceFactory implements DataSourceFactory {

        @Override
        public DbQuery createDbQuery(DbProperty property) {
            throw new UnsupportedOperationException("该类型数据源不支持:" + property.getDbType());
        }
    }
}
